package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"log"
)

type User struct {
	Id   int    `gorm:"primary_key"`
	Name string `grom:"type:varchar(50);not null;index:ip_idx"`
	Age  int    `gorm:"not null"`
	Addr string `grom:"type:varchar(50);not null;"`
}

func main() {

	db, err := gorm.Open("postgres", "host=localhost port=5432 user=postgres password=123456 dbname=postgres sslmode=disable ")
	if err != nil {
		fmt.Println("连接失败")
		return
	}
	fmt.Println("连接成功！")
	defer db.Close()

	//创建表Users
	if !db.HasTable(&User{}) {
		if err := db.CreateTable(&User{}).Error; err != nil {
			panic(err)
		} else {
			log.Println("创建成功！")
		}
	}

	user := &User{
		Id:   1,
		Name: "张三",
		Age:  23,
		Addr: "上海",
	}

	if err := db.Create(user).Error; err != nil {
		log.Println("插入失败", err)
		return
	} else {
		log.Println("插入成功")
	}

}
